// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package role

import (
	"audio-server/internal/model"
	"context"
	"database/sql"
	"encoding/json"
	"errors"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveRoleMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveRoleMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveRoleMenuLogic {
	return &SaveRoleMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveRoleMenuLogic) SaveRoleMenu(req *types.RoleSaveMenuReq) (resp bool, err error) {
	// todo: add your logic here and delete this line
	id := req.RoleId
	menuIds := req.MenuIds
	roleModel := model.NewSysRoleModel(l.svcCtx.Conn)
	role, err := roleModel.FindOne(l.ctx, int64(id))
	if err != nil {
		return false, errors.New("角色不存在")
	}
	jsonData, err := json.Marshal(menuIds)
	role.MenuIds = sql.NullString{String: string(jsonData), Valid: true}
	err = roleModel.Update(l.ctx, role)
	if err != nil {
		return false, errors.New("权限分配失败")
	}
	return true, nil
}
